# Importing Data
THAILAND <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Israel/Thailand.xlsx")

# Checking the Imported Data
View(THAILAND)

# Creating Time Series Data
THAILAND_ts <- ts(THAILAND, start=c(2007,02), end=c(2019,07), frequency=12)

# Viewing and Checking the Created Time Series Data
THAILAND_ts
sum(is.na(THAILAND_ts))
library(forecast)
THAILAND_ts <- tsclean(THAILAND_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(THAILAND_ts)
plot(aggregate(THAILAND_ts,FUN=mean))

# Decomposing
THAILAND_ts_decomp <- decompose(THAILAND_ts)
plot(THAILAND_ts_decomp)

# Testing for Stationarity
acf(THAILAND_ts, lag.max=20)
pacf(THAILAND_ts, lag.max=20)

# To see any seasonal effect
boxplot(THAILAND_ts~cycle(THAILAND_ts))

# To remove trend effect
THAILAND_ts_diff <- diff(THAILAND_ts)
plot(THAILAND_ts_diff)

# To remove variance effect
THAILAND_ts_log <- log(THAILAND_ts)
plot(THAILAND_ts_log)

# To remove both (Trend and Variance) effects
THAILAND_ts_both <- diff(log(THAILAND_ts))
plot(THAILAND_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(THAILAND_ts, lag.max=20)
acf(log(THAILAND_ts), lag.max=20)
acf(diff(THAILAND_ts), lag.max=20)
acf(diff(log(THAILAND_ts)), lag.max=20)
pacf(THAILAND_ts, lag.max=20)
pacf(log(THAILAND_ts), lag.max=20)
pacf(diff(THAILAND_ts), lag.max=20)
pacf(diff(log(THAILAND_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
THAILAND_ts_model <- auto.arima(THAILAND_ts)
THAILAND_ts_model
THAILAND_ts_model <- auto.arima(THAILAND_ts, ic="aic", trace = TRUE)
THAILAND_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(THAILAND_ts_model$resid)
acf(THAILAND_ts_model$residuals, main='ACF Residual')
pacf(THAILAND_ts_model$residuals, main='ACF Residual')
Box.test(THAILAND_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
THAILAND_ts_forecast <- forecast (THAILAND_ts_model, level=c(95), h=257)
plot(THAILAND_ts_forecast)
THAILAND_ts_forecast             


write.table(THAILAND_ts_forecast, file="Thailand_TSA.csv", sep=",")
